import socket
import threading


# 配置参数
LOCAL_HOST = '127.0.0.1'
PORT = 5000
BUFFER_SIZE = 4096

# 创建一个新的套接字对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# 绑定到指定的端口并开始监听
s.bind((LOCAL_HOST, PORT))
s.listen()
print("Listening on port: ", PORT)


def handler(client, addr):
    while True:
        data = client.recv(BUFFER_SIZE).decode('utf-8')

        if not data:
            break

        # 打印接收到的数据并将其回传给客户端
        print(f"Received from {addr[0]}:{addr[1]}: {data}")
        client.sendall(data.encode('utf-8'))

while True:
    client, addr = s.accept()
    print('Connected by', addr[0], ':', addr[1])
    threading.Thread(target=handler, args=[client, addr]).start()
